<template>
  <div class="page-container">
    <div class="top-row">
      <div class="top-info">
        <!-- <div>总营业额 {{ totalTurnover }} 元</div>
        <div>总利润 {{ totalProfit }} 元</div> -->
        <span class="span1 m-r2">总营业额</span>
        <span class="span2">{{ totalTurnover }}</span>
        <span class="span1 m-r6"> 元</span>
        <span class="span1 m-r2">总利润</span>
        <span class="span2">{{ totalProfit }}</span>
        <span class="span1 m-r6"> 元</span>
      </div>
      <div class="legend-wrapper">
        <div v-for="(legendItem, index) in legendData" :key="index" class="legend-item"
          @click="toggleSeriesVisibility(index)" :class="{ 'legend-item-hidden': !seriesVisibility[index] }">
          <span :style="{
            background: legendColors[index],
            color: 'none',
            width: '8px',
            height: '8px',
            display: 'inline-block',
            verticalAlign: 'text-top', // 调整垂直对齐方式
            lineHeight: '8px' // 设置行高与高度一致，使内容垂直居中
          }">

          </span>
          <span>{{ legendItem }}</span>
        </div>
      </div>
    </div>
    <div class="chart-container">
      <div ref="chartRef" style="width: 100%; padding: 0;" :style="{ height: eachartheight }"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, defineExpose } from 'vue';
import * as echarts from 'echarts';
const eachartheight = ref('289px')
const chartRef = ref<HTMLDivElement | null>(null);
const chartInstance = ref(null as any);
const chartData = ref<{ xaxis: string[], turnover: number[], profit: number[] }>({
  xaxis: [],
  turnover: [],
  profit: []
});

const totalTurnover = ref(0);
const totalProfit = ref(0);
const mealTimesName = ref('')
const legendData = ref(['营业额', '利润']);
const legendColors = ref(['rgba(20, 184, 165, 1)', 'rgba(255, 87, 106, 1)']);

const getChartOption = () => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        const turnoverValue = chartData.value.turnover[params.dataIndex];
        const profitValue = chartData.value.profit[params.dataIndex];
        const colorDot1 = `<span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background-color: rgba(20, 184, 165, 1); margin-right: 5px;"></span>`;
        const colorDot2 = `<span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background-color: rgba(255, 87, 106, 1); margin-right: 5px;"></span>`;
        return `${params.name}（${mealTimesName.value}）<br/>${colorDot1}营业额: ${turnoverValue} 元<br/>${colorDot2}利润: ${profitValue} 元`;
      },
      backgroundColor: 'rgba(0, 0, 0, 0.7)',
      textStyle: {
        color: '#fff'
      }
    },
    grid: {
      left: '54px',
      right: '4%',
      top: '10%', // 适当减少图表上方空白
      // bottom: '10%'
    },
    legend: {
      show: false
    },
    xAxis: [
      {
        type: 'category',
        axisTick: { show: false },
        data: chartData.value.xaxis,
        axisLabel: {
          formatter: function (value) {
            if (value.length <= 5) {
              return value.split('').join('\n');
            }
            const firstFourChars = value.slice(0, 4).split('').join('\n');
            return `${firstFourChars}\n...`;
          }
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '金额 (元)',
        min: 0,
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            width: 1
          }
        },
        nameTextStyle: {

          padding: [0, 0, 0, -40] // 左padding负值，向左移动

        },
        axisLabel: {

          align: 'right',

          margin: 0 // 调整标签与轴的距离

        },
        offset: 10
      }
    ],
    series: [
      {
        name: '营业额',
        type: 'bar',
        barWidth: '6px',
        itemStyle: {
          color: 'rgba(20, 184, 165, 1)'
        },
        data: chartData.value.turnover
      },
      {
        name: '利润',
        type: 'bar',
        barWidth: '6px',
        itemStyle: {
          color: 'rgba(255, 87, 106, 1)'
        },
        data: chartData.value.profit
      }
    ]
  };
};

const initChart = async (row) => {
  if (chartRef.value) {
    // 销毁旧图表实例（防止内存泄漏）
    if (chartInstance.value) {
      chartInstance.value.dispose();
      chartInstance.value = null;
    }
    // 设置新高度
    eachartheight.value = row.height ? row.height : '289px';
    // 等待 DOM 更新
    await nextTick(); // ⚠️ 关键点：确保高度已应用到 DOM
    // 初始化新图表
    chartInstance.value = echarts.init(chartRef.value);
    chartData.value = {
      'xaxis': row.xaxis,
      'turnover': row.series[0]?.data || [],
      'profit': row.series[1]?.data || []
    };
    mealTimesName.value = row.mealTimesName;
    totalTurnover.value = row.extra.totalSaleAmount;
    totalProfit.value = row.extra.totalProfitAmount;
    const option = getChartOption();
    chartInstance.value.setOption(option);
    // 立即调整图表尺寸
    if (chartInstance.value) {
      // chartInstance.value.resize(); // ⚠️ 确保图表适应新高度
    }
  }
};

// 监听 chartData 的变化，当数据变化时重新设置选项
watch(chartData, () => {
  if (chartInstance.value) {
    const option = getChartOption();
    chartInstance.value.setOption(option);
  }
}, { deep: true });

const seriesVisibility = ref([true, true]);

// 优化切换方法
const toggleSeriesVisibility = (index: number) => {
  if (!chartInstance.value) return;

  const seriesName = legendData.value[index];
  // 使用标准切换API
  chartInstance.value.dispatchAction({
    type: 'legendToggleSelect',
    name: seriesName
  });
  seriesVisibility.value[index] = !seriesVisibility.value[index]
};

defineExpose({
  initChart
})
// 优化监听器
// watch(
//   () => {
//     // 安全访问配置
//     if (chartInstance.value?.getOption) {
//       const series = chartInstance.value.getOption().series || [];
//       return series.map(s => s.show !== false);
//     }
//     return [];
//   },
//   (newVisibility) => {
//     if (newVisibility.length === 2) {
//       seriesVisibility.value = newVisibility;
//     }
//   },
//   { deep: true, immediate: true }
// );

// // 添加图表实例监听
// watch(chartInstance, (newInstance) => {
//   if (newInstance) {
//     // 初始化同步状态
//     const initialSeries = newInstance.getOption().series || [];
//     seriesVisibility.value = initialSeries.map(s => s.show !== false);
//   }
// });
onMounted(() => {
  // initChart();
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;

  .span1 {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: rgba(0, 0, 0, 0.65);
  }

  .span2 {
    font-family: DIN, DIN;
    font-weight: bold;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.85);
    margin-right: 2px;
  }
}

.top-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px; // 减少 top-row 与图表之间的距离
}

.top-info {
  display: flex;
  align-items: center;
}

.chart-container {
  width: 100%;
}

.legend-wrapper {
  display: flex;
  gap: 10px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;

  // 悬停效果（可选）
  &:hover {
    background: rgba(0, 0, 0, 0.04);
  }

  &-hidden {
    span:first-child {
      // 颜色方块
      filter: grayscale(100%) brightness(1.5);
      opacity: 0.6;
    }

    span:last-child {
      // 文字部分
      color: #999 !important;
      position: relative;

      // &::after {
      //   content: '';
      //   position: absolute;
      //   left: 0;
      //   top: 50%;
      //   width: 100%;
      //   height: 1px;
      //   background: #999;
      //   transform: translateY(-50%);
      // }
    }
  }
}
</style>